package com.ozo.boot.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ozo.boot.common.core.exception.ServiceException;
import com.ozo.boot.common.file.config.FileStoreProperties;
import com.ozo.boot.common.file.strategy.FileStrategy;
import com.ozo.boot.system.entity.SysFile;
import com.ozo.boot.system.exception.SystemExceptionEnum;
import com.ozo.boot.system.mapper.SysFileMapper;
import com.ozo.boot.system.service.ISysFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ozo.boot.system.pojo.vo.SysFileVO;
import com.ozo.boot.common.file.service.FileTemplate;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 文件 服务实现类
 * </p>
 *
 * @author qiangesoft
 * @since 2024-07-11
 */
@RequiredArgsConstructor
@Service
public class SysFileServiceImpl extends ServiceImpl<SysFileMapper, SysFile> implements ISysFileService {

    private final FileTemplate fileTemplate;

    private final FileStoreProperties fileStoreProperties;

    @Override
    public SysFileVO upload(MultipartFile file) {
        String storePath;
        try {
            storePath = fileTemplate.uploadFile("avatar", file);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException(SystemExceptionEnum.FILE_UPLOAD_FAIL);
        }

        String fileName = storePath.substring(storePath.lastIndexOf(FileStrategy.SLASH) + 1);
        String originalFilename = StrUtil.isNotBlank(file.getOriginalFilename()) ? file.getOriginalFilename() : fileName;
        String suffix = fileName.substring(fileName.lastIndexOf(FileStrategy.POINT) + 1);

        SysFile sysFile = new SysFile();
        sysFile.setOriginalName(originalFilename);
        sysFile.setFileName(fileName);
        sysFile.setFileSize((int) file.getSize());
        sysFile.setFileSuffix(suffix);
        sysFile.setFilePath(storePath);
        baseMapper.insert(sysFile);

        SysFileVO sysFileVO = BeanUtil.copyProperties(sysFile, SysFileVO.class);
        sysFileVO.setFileUrl(fileStoreProperties.getNginxHost() + FileStrategy.SLASH + storePath);
        return sysFileVO;
    }

}
